// message.js
const requester = require('../../common/requester.js');
const $$onLoad = require('../../appLoaded/onLoad');
const fans = require('../../utils/fans.js');

const pageConfig = {
    follow: {
        title: '关注',
        tip: '关注',
        url: requester.service.queryMyFollowedUsers
    },
    fans: {
        title: '粉丝',
        tip: '粉丝',
        url: requester.service.queryMyFansUsers
    }
};
Page({
    data: {
        followedUsers: []
    },

    onLoad: function (param) {
        wx.showToast({
            title: '加载中....',
            icon: 'loading',
            duration: 10000
        });
        $$onLoad()
            .then(() => {
                this.init(param);
            })
    },
    /***
     *
     * @param param type=follow ,关注人列表
     * @param param type=fan ,粉丝列表
     */
    init: function (param) {
        let type = param.type,
            id = param.id;

        this.setData({
            userId: param.id,
            tip: pageConfig[type].tip
        });
        wx.setNavigationBarTitle({
            title: pageConfig[type].title
        });
        this.getList(type, id);
    },


    getList: function (type, id) {
        requester.request({
            url: pageConfig[type].url,
            data: {
                userId: id
            }
        }).then(res => {
            let followedUsers = res.data.followedUsers;
            this.setData({
                followedUsers: followedUsers.length ? followedUsers : null
            }, () => {
                wx.hideToast();
            });
        });
    },

    getItemId: function (e) {
        return e.target.dataset.id;
    },

    follow: function (e) {
        let id = e.target.dataset.userId;
        let idx = e.target.dataset.idx;
        fans.follow(id).then((res) => {
            if (res) {
                wx.showToast({
                    title: '关注成功'
                });
                let data = this.data.followedUsers;
                data[idx].isFollowed = 1;
                this.setData({
                    followedUsers: data
                })
            }
        })
    },
    unfollow: function (e) {
        let id = e.target.dataset.userId;
        let idx = e.target.dataset.idx;
        fans.unfollow(id).then((res) => {
            if (res) {
                wx.showToast({
                    title: '已取消关注'
                });
                let data = this.data.followedUsers;
                data[idx].isFollowed = 0;
                this.setData({
                    followedUsers: data
                })
            }
        })
    },
    jumpUser: function (e) {
        let userId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '../thirdUser/thirdUser?' + "userId=" + userId
        });
    }
});